package com.zhentao.email;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class EmailUtil {

    // 发件人邮箱相关配置，这里假设使用QQ邮箱，可替换为其他邮箱对应配置
    private static final String SMTP_HOST = "smtp.qq.com";
    private static final String SMTP_PORT = "465";
    // 发件人邮箱地址，替换成真实的邮箱地址
    private static final String FROM_EMAIL = "song18333983823@qq.com";
    // 发件人邮箱密码或者授权码（不是登录密码，QQ邮箱等需获取授权码用于第三方登录）
    private static final String PASSWORD = "mjgcihlmdyicdfec";

    /**
     * 封装的发送邮件方法
     *
     * @param to      收件人邮箱地址
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public static void sendEmail(String to, String subject, String content) {
        Properties properties = new Properties();
        properties.put("mail.smtp.host", SMTP_HOST);
        properties.put("mail.smtp.port", SMTP_PORT);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(FROM_EMAIL, PASSWORD);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(FROM_EMAIL));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setText(content);

            Transport.send(message);
            System.out.println("邮件发送成功");
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 收件人邮箱地址示例
        String to = "3063944438@qq.com";
        // 邮件主题示例
        String subject = "测试123";
        // 邮件内容示例
        String content = "这是一封通过封装方法发送的测试邮件内容";
        sendEmail(to, subject, content);
    }
}
